<?php
	include_once './init.php';
	include_once './login.php';
	include_once './session.php';

	if(isLogin()){
		$method = $_POST["method"];
		switch ($method) {
			case 'video':
				addVideo();
				break;
			case 'formData':
				addVideoData();
				break;
		}
	}else{
		showmsg($login = array('status' => 'no'));
	}

	function addVideo(){
		if(empty($_FILES)) {
			showmsg($upload = array(
				'status' => 'fail2',
				'message' => 'upload failed'
				)
			);
			return;
		}
		if($_FILES[files]['error'] > 0) {
			showmsg($upload = array(
				'status' => 'error',
				'message' => 'upload failed'
				)
			);
			return;
		}
		$videoName = $_FILES["files"]["name"];
		$videoSize = $_FILES["files"]["size"];
		$videoType = $_FILES["files"]["type"];
		$description = $_POST['description'];
		$sorts = array("动画" , "电影" , "电视剧" , "微电影");
		$sort = $_POST['sort'];
		$sortName = $sorts[$sort];

		$videoTempPath = $_FILES["files"]["tmp_name"];
		$videoPath = "media/".$videoName;
		$status = move_uploaded_file($videoTempPath , $videoPath);
		if(!$status){
			showmsg($upload = array(
				'status' => 'move',
				'message' => 'upload failed',
				'files' => $_FILES["files"],
				)
			);
			return;
		}

		$db = initDatabase();
		$resultOfSelect = $db -> get_row("select * from video where videoName='$videoName'");
		//有相同的视频文件
		if($resultOfSelect){
			showmsg($upload = array(
				'status' => 'fail',
				'message' => 'this video has existed'
				)
			);
			return;
		}
		$userId = $_SESSION["userId"];
		$resultOfInsert = $db -> query("insert into video (videoName, videoSize, videoType, videoSort, videoPath, uploaderId, videoDescription) values ('$videoName', '$videoSize', '$videoType', '$sortName', '$videoPath', '$userId', '$description')");
		
		$resultOfSelect = $db -> get_row("select videoId from video where videoName='$videoName'");
		$videoId = $resultOfSelect ->videoId;

		if($resultOfInsert){
			showmsg($upload = array(
				'status' => 'success',
				'videoId' => $videoId 
				)
			);
		}else{
			showmsg($upload = array(
				'status' => 'fail1',
				'message' => 'upload failed',
				'files' => $_FILES["files"],
				)
			);
		};
	}
	function addVideoData(){
		$sorts = array("动画" , "电影" , "电视剧" , "微电影");
		$sort = $_POST["sort"];
		$sortName = $sorts[$sort];
		$description = $_POST["description"];
		$videoId = $_POST["videoId"];

		$uploaderId = $_SESSION["userId"];

		$db = initDatabase();
		$resultOfSelect = $db->get_row("select * from video where videoId='$videoId'");
		$status = $db->query("update video set videoSort='$sortName' , videoDescription='$description' , uploaderId='$uploaderId' where videoId='$videoId'");
		$resultOfSelect = $db->get_row("select * from video where videoId='$videoId'");
		if($status){
			showmsg($upload = array(
					'status' => 'success',
					'videoId' => $videoId
					)
				);
		}else{
			showmsg($upload = array(
				'status' => 'fail'
				)
			);
		}
	}
?>